package com.yyc.tool.service.impl;

import com.yyc.tool.domain.Client;
import com.yyc.tool.repository.ClientRepository;
import com.yyc.tool.service.ClientService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Slf4j
@Service
public class ClientServiceImpl implements ClientService {

    private PasswordEncoder passwordEncoder;
    private ClientRepository clientRepository;

    @Autowired
    public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    @Autowired
    public void setClientRepository(ClientRepository clientRepository) {
        this.clientRepository = clientRepository;
    }

    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        Optional<Client> optionalClient = clientRepository.findById(clientId);
        return optionalClient.orElse(null);
    }

    @Override
    public Client addClient(String name) {
        Client client = new Client();
        client.setName(name);
        String clientSecret = RandomStringUtils.randomAlphanumeric(16);
        log.info("客户端密码:{}",clientSecret);
        client.setDescription("token测试程序");
        client.setClientSecret(passwordEncoder.encode(clientSecret));
        return clientRepository.saveAndFlush(client);
    }

    @Override
    public Client addClientForMe(String name, String password) {
        Client client = new Client();
        client.setName(name);
        String clientSecret = "123456";
        log.info("客户端密码:{}",clientSecret);
        client.setDescription("token测试程序");
        client.setClientSecret(passwordEncoder.encode(clientSecret));
        return clientRepository.saveAndFlush(client);
    }
}
